package net.thetabx.ftdba.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;


import net.thetabx.ftdba.RStatus;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

public class DefaultHttpData implements HttpData {

	//private String status = "ok";
	private RStatus status = RStatus.NOT_ACTIVE; 
	private String redirect;
	private List<String> content;
	private StringBuilder contentSb;
	
	public DefaultHttpData(HttpResponse response) {
		if(response == null) {
			status = RStatus.NO_RESPONSE;
			return;
		}
		
		Header location = response.getLastHeader("location");
		if(location != null) {
			status = RStatus.REDIRECT;
			this.redirect = location.getValue();
			return;
		}
		
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(response.getEntity().getContent(), "iso-8859-1");
		} catch (Exception e) {
			status = RStatus.INPUTSTREAM_ERROR;
		}
		
		if(isr == null) {
			status = RStatus.INPUTSTREAM_EMPTY;
			return;
		}
		
		String line = "";
		contentSb = new StringBuilder();
		BufferedReader br = new BufferedReader(isr);

	    try {
			while ((line = br.readLine()) != null) { 
				contentSb.append(line); 
			}
		} catch (IOException e) {
			status = RStatus.BUFFEREDSTREAM_CANTREAD;
		}

		status = RStatus.ENDED;
	}
	
	public RStatus getStatus() {
		return status;
	}
	
	public String getRedirect() {
		return redirect;
	}
	
	public String[] getContent() {
		return (String[]) content.toArray();
	}
	
	public StringBuilder getContentSb() {
		return contentSb;
	}
}
